package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.AttrTrashEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.AttrTrashModel;
import com.xbongbong.paas.pojo.attrtrash.AttrTrashFixBugDTO;
import com.xbongbong.paas.pojo.attrtrash.FormAttrTrashDTO;
import com.xbongbong.paas.script.pojo.dto.ScriptBaseDTO;
import com.xbongbong.paas.service.impl.PaasFormAttrTrashServiceImpl;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.help.SysEnvHelp;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 字段回收站脚本
 * @author 魏荣杰
 * @date 2021/3/8 17:14
 * @since
 * @version
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/trash")
public class AttrTrashScriptController {

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private AttrTrashModel attrTrashModel;
    @Resource
    private PaasFormAttrTrashServiceImpl paasFormAttrTrashService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private SysEnvHelp sysEnvHelp;

    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid ScriptBaseDTO scriptBaseDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(scriptBaseDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                boolean isGrayEnvironmentEnable = sysEnvHelp.isGrayEnvironmentEnable();
                Map<String, Object> param = new HashMap<>();
                param.put("del", 0);
                //正常使用
                param.put("status", 1);
                param.put("orderByStr", "add_time asc, corpid asc");
                param.put("columns", "corpid");
                param.put("start", 0);
                param.put("pageNum", 5000);
                boolean flag = true;
                while (flag) {
                    List<CompanyEntity> entitys = companyModel.findEntitys(param);
                    if (entitys.size() == 0) {
                        flag = false;
                    } else {
                        param.put("corpidGte", entitys.get(entitys.size() - 1).getCorpid());
                        for (CompanyEntity entity : entitys) {

                            if (sysEnvHelp.isGrayEnvironment()) {
                                if (!isGrayEnvironmentEnable) {
                                    continue;
                                }
                                if (!sysEnvHelp.checkIsCrayCompany(entity.getCorpid())) {
                                    continue;
                                }
                            } else {
                                if (isGrayEnvironmentEnable) {
                                    if (sysEnvHelp.checkIsCrayCompany(entity.getCorpid())) {
                                        continue;
                                    }
                                }
                            }

                            Map<String, Object> params = new HashMap<>();
                            params.put("corpid", entity.getCorpid());
                            params.put("del", DelEnum.NORMAL.getDel());
                            params.put("recover", 0);
                            params.put("endAddTime", DateTimeUtil.getTodayInt() - 45 * 86400);
                            List<AttrTrashEntity> trashEntityList = attrTrashModel.findEntitys(params);
                            paasFormAttrTrashService.trashDeleteJobs(trashEntityList, null);
                        }

                    }
                }

                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/fixBug", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid AttrTrashFixBugDTO attrTrashFixBugDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(attrTrashFixBugDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                String corpid = attrTrashFixBugDTO.getCorpid();
                AttrTrashEntity attrTrashEntity = attrTrashModel.getByKey(attrTrashFixBugDTO.getTrashId(), corpid);
                if (Objects.isNull(attrTrashEntity)) {
                    return "回收站不存在";
                }
                PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(attrTrashFixBugDTO.getCorpid(), attrTrashEntity.getFormId(), attrTrashEntity.getBusinessType());
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getAllSubFormExplainMap(paasFormExplainEntity.getExplains());
                if (explainMap.containsKey(attrTrashFixBugDTO.getAttr()) && !Objects.equals(2, explainMap.get(attrTrashFixBugDTO.getAttr()).getIsOpen())) {
                    return "字段未进回收站，不允许删除";
                }
                if (XbbRefTypeEnum.workOrderV2Form().contains(paasFormExplainEntity.getBusinessType())) {
                    return "工单业务，不可以使用该接口";
                }
                paasFormAttrTrashService.trashDeleteJobs(Collections.singletonList(attrTrashEntity), null);
                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 单个表单的字段到期的回收
     * @param deleteAttrTrashDTO
     * @param br
     * @return
     * @throws XbbException
     */
    @RequestMapping(value = "/fixBugByFormId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixBugByFormId(@RequestBody @Valid FormAttrTrashDTO deleteAttrTrashDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(deleteAttrTrashDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                String corpid = deleteAttrTrashDTO.getCorpid();
                Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                params.put(StringConstant.CORPID, corpid);
                params.put("del", DelEnum.NORMAL.getDel());
                params.put("formId", deleteAttrTrashDTO.getFormId());
                params.put("businessType", deleteAttrTrashDTO.getBusinessType());
                params.put("recover", 0);
                params.put("endAddTime", DateTimeUtil.getTodayInt() - 45 * 86400);
                List<AttrTrashEntity> trashEntityList = attrTrashModel.findEntitys(params);
                if (CollectionUtils.isEmpty(trashEntityList)) {
                    return "字段回收站为空";
                }

                paasFormAttrTrashService.trashDeleteJobs(trashEntityList, null);
                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
